<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="全部" name="allApprovals" />
          <el-tab-pane label="我发起的" name="myApprovals" />
          <el-tab-pane label="待审批" name="pending" />
        </el-tabs>
        <!--  -->
        <el-row class="ap_ty_st">
          <span class="strong">
            审批类型：
          </span>
          <el-radio-group v-model="radio" @change="radioChange">
            <el-radio v-for="item in ApprovalsType" :key="item.key" :label="item.key">{{ item.name }}</el-radio>
          </el-radio-group></el-row>

        <el-row v-if="activeName!=='pending'" type="flex" class="ap_ty_st">
          <span class="strong">
            审批状态：
          </span>
          <el-checkbox-group v-model="checkList" @change="changeSelectBox">
            <el-checkbox v-for="item in approvalsState" :key="item.id" :label="item.id">{{ item.value }}</el-checkbox>
          </el-checkbox-group>
        </el-row>

        <!-- 申请列表区 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          class="approvaleTable"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column type="index" label="序号" width="55" />
          <el-table-column label="审批类型" prop="processName" />
          <el-table-column
            v-if="activeName!=='myApprovals'"
            label="申请人"
            prop="username"
          />
          <el-table-column v-if="activeName!=='pending'" label="当前审批人" prop="procCurrNodeUserName" />
          <el-table-column label="申请时间" prop="procApplyTime">
            <template #default="{row}">
              {{ row.procApplyTime |formatDate('yyyy/MM/dd hh:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column label="审批状态" prop="processState">
            <template #default="{row}">
              <span v-if="row.processState==='1'"> <span class="notYeah circle" /> 审批中</span>
              <span v-if="row.processState==='2'"><span class="parss circle" />审批驳回</span>
              <span v-if="row.processState==='3'"><span class="unparss circle" />已撤销</span>
              <span v-if="row.processState==='4'"><span class="none circle" />审批通过</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="210">
            <template #default="{row}">
              <el-button type="primary" size="mini" @click="checkApproval(row.processId)">查看</el-button>
              <el-button v-if="row.userId===userId&&row.processState==='1'&&activeName==='myApprovals'" type="primary" size="mini" @click="replyApproval('撤销审核',row.processId,'4')">撤销</el-button>
              <el-button v-if="row.processState==='1'&&activeName!=='myApprovals' " type="primary" size="mini" @click="replyApproval('通过审核',row.processId,'2')">通过</el-button>
              <el-button v-if="row.processState==='1'&&activeName!=='myApprovals'" type="primary" size="mini" @click="replyApproval('驳回审核',row.processId,'3')">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end">
          <el-pagination
            :current-page="page.page"
            :page-sizes="[5, 10, 20, 40]"
            :page-size="page.size"
            layout="sizes, prev, pager, next, jumper"
            :total="page.total"
            class="ApprovalsPagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog :visible="showDialog" :title="dialogForm.processName" @close="showDialog=false">
        <div>
          <div class="myapply">
            <span class="picCircle">
              <img src="@/assets/common/img.jpeg" class="img">
            </span>
            <span class="rightContent">
              <strong>{{ dialogForm.username }}</strong>
              <p>部门:  {{ dialogForm.departmentName }}</p>
              <p>入职时间:  {{ dialogForm.timeOfEntry |formatDate('yyyy/MM/dd hh:mm:ss') }}</p>
            </span>
          </div>
          <!-- <hr> -->
          <!-- 请假表单 -->
          <el-form v-if="dialogForm.processName==='请假'" ref="form" :model="dialogForm" label-width="80px">
            <el-form-item label="请假类型" style="width:300px">
              <el-input v-model="dialogForm.processName" disabled />
            </el-form-item>
            <el-form-item label="开始时间" style="width:300px">
              <el-input v-model="procData.startTime" disabled type="datetime" prefix-icon="el-icon-date" />
            </el-form-item>
            <el-form-item label="结束时间" style="width:300px">
              <el-input v-model="procData.endTime" disabled type="datetime" prefix-icon="el-icon-date" />
            </el-form-item>
            <el-form-item label="请假时长" style="width:300px">
              <el-input v-model="procData.duration" disabled />
            </el-form-item>
            <el-form-item label="申请原因" style="width:400px">
              <el-input v-model="procData.reason" disabled type="textarea" />
            </el-form-item>
          </el-form>

          <!-- 离职表单 -->
          <el-form v-if="dialogForm.processName==='离职'" :model="dialogForm" label-width="100px">
            <el-form-item label="期望离职时间" style="width:350px">
              <el-input v-model="procData.end_time" disabled type="datetime" prefix-icon="el-icon-date" />
            </el-form-item>
            <el-form-item label="离职原因" style="width:400px">
              <el-input v-model="procData.reason" disabled type="textarea" />
            </el-form-item>
          </el-form>

          <!-- 加班表单 -->
          <el-form v-if="dialogForm.processName==='加班'" :model="dialogForm" label-width="100px">
            <el-form-item label="补偿方式">
              调休
            </el-form-item>
            <el-form-item label="加班开始时间" style="width:350px">
              <el-input v-model="procData.start_time" disabled type="datetime" prefix-icon="el-icon-date" />
            </el-form-item>
            <el-form-item label="加班结束时间" style="width:350px">
              <el-input v-model="procData.end_time" disabled type="datetime" prefix-icon="el-icon-date" />
            </el-form-item>
            <el-form-item label="申请原因" style="width:400px">
              <el-input v-model="procData.reason" disabled type="textarea" />
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>

      <el-dialog :visible="showReply" :title="replyTitle" width="30%" @close="btnCancle">
        <el-form>
          <el-form-item>
            <el-input v-model="replyForm.handleOpinion" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="end">
              <el-button>取消</el-button>
              <el-button type="primary" @click="btnOk">确认</el-button>
            </el-row>
          </el-form-item>
        </el-form>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getApprovalsList, getApprovalsType, postApprovals } from '@/api/approvals'
import { getApprovalsDetail } from '@/api/user'
import approvalsEnum from '@/api/constant/approvals'
// import { getUserDetailById } from '@/api/user'
export default {

  data() {
    return {
      activeName: 'allApprovals',
      radio: '',
      checkList: [],
      tableData: [],
      page: {
        page: 1,
        size: 5,
        processKey: '',
        total: 1
      },
      username: this.$store.getters.name, // 用户名
      userId: this.$store.getters.userId, // 用户ID
      currentUserList: [], // 当前用户列表
      pendingList: [], // 待审核列表
      allApprovalsList: [], // 所有审批列表
      ApprovalsType: [], // 审批类型数组
      renderList: [], // 渲染的数组
      approvalsState: approvalsEnum.approvalState, // 审批状态枚举
      showDialog: false,
      dialogForm: {},
      procData: {},
      showReply: false,
      replyTitle: '',
      replyForm: {
        handleOpinion: '',
        handleUserId: '',
        processId: '',
        handleType: ''
      }
    }
  },
  async mounted() {
    // 获取审批列表
    this.getApprovalsList()
    // 获取所有审批类型
    this.ApprovalsType = await getApprovalsType()
  },
  methods: {
    // 点击切换标签页触发
    async  handleClick(value) {
      // console.log(value.paneName)
      // 改变 tabs 激活标签
      this.activeName = value.paneName
      // 当点击的不是 allApprovals 时 进行不同内容的筛选渲染
      if (this.activeName !== 'allApprovals') {
        // console.log(this.radio, 11111)
        this.renderList = this.filterApprovalsList()
        // this.page.total = reList.length
        this.filterPageList(this.renderList)
      } else {
        // 当切换回所有列表时，调用获取所有默认数据
        this.getApprovalsList()
      }
    },
    // 获取列表数据
    async  getApprovalsList() {
      // console.log(this.page)
      // 发送获取 当前page 状态的审批列表请求
      const { rows, total } = await getApprovalsList(this.page) // 1,2
      this.tableData = rows
      this.page.total = total
      // console.log(total, 99996)
      // console.log(rows)

      // 获取所有审批列表
      if (this.allApprovalsList.length === 0) {
        this.getAll()
      }
    },
    // 一页数据条数发生改变时触发
    handleSizeChange(value) {
      // console.log(value, 666)
      this.page.size = value
      // 当前标签页为 全部审批
      if (this.activeName === 'allApprovals') {
        this.getApprovalsList()
      }
      // const changePage = this.page.page
      // 过滤当前
      this.filterPageList(this.renderList) // this.renderList
    },
    // 当前第几页改变时触发
    handleCurrentChange(value) {
      // console.log(value, 55)
      this.page.page = value
      if (this.activeName === 'allApprovals') {
        this.getApprovalsList()
      }
      // 过滤
      this.filterPageList(this.renderList)
    },
    // 根据当前分页标签筛选出 符合的数据
    filterApprovalsList() {
      // 获取所有审批列表
      // this.getAll()
      if (this.activeName === 'myApprovals') {
        // 过滤出当前用户的审批列表
        // 改变数据总数
        // console.log(this.allApprovalsList, 9999)
        this.currentUserList = this.allApprovalsList.filter(item => item.userId === this.userId)
        // this.page.total = this.currentUserList.length
        // 单选框有值时
        if (this.radio) {
          const lengthList = this.currentUserList.filter(item => item.processKey === this.radio)
          // 复选框有值时
          if (this.checkList.length !== 0) {
            const checkBoxList = this.filterCheckbox(lengthList)
            this.page.total = checkBoxList.length
            return checkBoxList
          }
          // console.log(lengthList)
          this.page.total = lengthList.length
          return lengthList
        } else {
          if (this.checkList.length !== 0) {
            const checkBoxList = this.filterCheckbox(this.currentUserList)
            this.page.total = checkBoxList.length
            return checkBoxList
          } else {
            this.page.total = this.currentUserList.length
            // 过滤列表 // 当标签页选中 myApprovals 时筛选 currentUserList 列表
            return this.currentUserList
          }
          // 改变当前分页标签总数
        }
      } else {
        this.pendingList = this.allApprovalsList.filter(item => {
          // 当前待审批 processState状态码为 '1' procCurrNodeUserName 为审核者
          return item.processState === '1' && item.procCurrNodeUserName.indexOf(this.username) !== -1
        })
        // 单选框有值
        if (this.radio) {
          this.page.total = (this.pendingList.filter(item => item.processKey === this.radio)).length
          return this.pendingList.filter(item => item.processKey === this.radio)
        } else {
          this.page.total = this.pendingList.length
          return this.pendingList
        }
        // 当标签页选中 pending 时筛选 pendingList 列表
      }
    },
    // 获取所有审批列表的方法封装
    async getAll() {
      const { rows } = await getApprovalsList({ page: 1, size: this.page.total })
      this.allApprovalsList = rows
      // console.log(this.allApprovalsList, 6636, '所有申请列表')
      // console.log('被触发了')
    },
    // 单选框选中改变时
    async  radioChange(value) {
      console.log(value, 9999, this.radio)
      this.page.processKey = value
      if (this.activeName === 'allApprovals') {
        this.getApprovalsList()
      } else {
        // 与 tabs 标签点击时触发数据筛选
        this.renderList = this.filterApprovalsList()
        // 根据当前分页标签进行数据渲染
        this.filterPageList(this.renderList)
      }
    },
    // 根据当前分页标签进行数据筛选的方法封装
    filterPageList(data) {
      // 当前分页标签的 page*size 大于渲染数据数目时，不需要进行分页筛选
      if (data.length <= this.page.page * this.page.size) {
        this.tableData = data
        // console.log(11)
      } else {
        this.tableData = data.filter((item, index) => (this.page.page - 1) * this.page.size <= index && index < this.page.size * this.page.page)
      }
    },
    async changeSelectBox(data) {
      // console.log(this.checkList)
      this.renderList = this.filterApprovalsList()
      this.filterPageList(this.renderList)
    },
    // 复选框过滤函数封装
    filterCheckbox(data) {
      return data.filter(item => this.checkList.join().indexOf(item.processState) !== -1)
    },
    async checkApproval(id) {
      this.showDialog = true
      // this.dialogForm
      this.dialogForm = await getApprovalsDetail(id)
      this.procData = JSON.parse(this.dialogForm.procData)
      console.log(this.dialogForm)
    },
    replyApproval(title, id, state) {
      // 弹出窗标题渲染
      this.replyTitle = title
      // 表单赋值
      this.replyForm.processId = id
      this.replyForm.handleType = state
      this.replyForm.handleUserId = this.userId
      // 弹出弹窗
      this.showReply = true
    },
    btnCancle() {
      // 二次校验
      // this.$confirm('关闭后将会清空，是否确认')
      // 清空表单
      this.replyForm = {
        handleOpinion: ''
        // processId: '',
        // handleType: ''
      }
      this.showReply = false
    },
    async  btnOk() {
      // 二次校验s
      await this.$confirm('是否请确认审批？')
      console.log(this.replyForm)
      // 发请求
      await postApprovals(this.replyForm)
      // 提示
      this.$message.success('操作成功')
      // 关闭弹窗
      this.showReply = false
      // 刷新渲染
      this.getApprovalsList()
      this.getAll()
    }

  }

}
</script>

<style lang="scss" scoped>
::v-deep  .el-card__body{
  padding: 5px 20px;
}
.strong{
  font-weight: 700;
}

.ap_ty_st{
  margin: 15px 0;
}
.approvaleTable{
  margin-top: 20px;
.circle{
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  margin-bottom: 2px;
  margin-right: 5px;
}
.notYeah{
  background-color: #108ee9;
}

.parss{
  background-color: #00a854;
}

.unparss{
  background-color: #f04134;
}

.none{
  background-color: #bfbfbf;
}
}
.ApprovalsPagination{
  margin-top: 20px;
}

::v-deep .el-table__header{
  border-bottom: 2px solid #e8e8e8;
}
::v-deep .el-table__row{
  border-bottom: 0px;
}

.myapply{
    display: flex;
    font-size: 14px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 20px;
    .img{
      width: 100px;
      // height: 80px;
      border-radius: 50%;
      border: 1px solid #ccc;
    }
    .rightContent{
      margin-left: 20px;
    }

  }
</style>
